package net.wanho.shiro.relam;

import net.wanho.po.sys.User;
import net.wanho.service.sys.MenuServiceI;
import net.wanho.service.sys.UserServiceI;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    private UserServiceI userService;

    @Autowired
    private MenuServiceI menuService;

    // 认证(登录)
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        String username = usernamePasswordToken.getUsername();
        // 根据用户名从数据库查询
        User dbUser = userService.findUserByName(username) ;
        //当authenticationToken令牌中的密码与数据库密码一致，即成功
        return new SimpleAuthenticationInfo(dbUser,dbUser.getPassword(), ByteSource.Util.bytes(dbUser.getPhonenumber()),getName());
    }

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        // 根据用户名从数据库查邮所有权限资源

        // 获取身份
        User  user = (User) principalCollection.getPrimaryPrincipal();
        // 从身份中获取用户Id
        Long userId = user.getUserId();
        // 如果用户id为1 ，则是管理员
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        if(userId.intValue()==1){
            simpleAuthorizationInfo.addStringPermission("*:*:*");
        }else{
            // 根据用户id从数据库查询
             Set<String> perms = menuService.findMenusByUserId(userId);
            simpleAuthorizationInfo.addStringPermissions(perms);
        }

        return  simpleAuthorizationInfo;
    }


}
